package com.augurit.gzcgwsp.mail.service.impl;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.augurit.common.dao.OmUserDao;
import com.augurit.common.entity.OmUser;
import com.augurit.gzcgwsp.common.util.WSClient;
import com.augurit.gzcgwsp.mail.service.ISendOaService;
import com.augurit.gzcgwsp.printDoc.dao.YwPrintDocDao;
@Service
@Transactional
/**
 * oa发送service
 */
public class SendOaServiceImpl implements ISendOaService{
	private static final Logger log=Logger.getLogger( SendOaServiceImpl.class);
		@Autowired
		private YwPrintDocDao ywPrintDocDao;
		@Autowired
		private OmUserDao  omUserDao;
		
		/**
		 * 发行政许可书到oa
		 */
		public void sendDoc(){
			StringBuffer sb=new StringBuffer();
			sb.append("select t.template_code,t.bus_memo1,doc.* from ( \r");
			sb.append("select   temp.template_code,ins.master_entity_key,ins.bus_memo1 from \r");
			sb.append("JBPM4_HIST_PROCINST proc,WF_BUS_INSTANCE ins,WF_BUS_TEMPLATE temp \r");
			sb.append(" where proc.id_=ins.proc_inst_id  \r");
			sb.append("and ins.template_id=temp.id    and proc.state_='ended' ) \r");
			sb.append(" t inner join YW_PRINT_DOC doc on doc.yw_id=t.master_entity_key and \r");
			sb.append(" doc.template_code=t.template_code  and doc.file_code='zyxzxkjds' and doc.sendoa is  null \r");
			List list=this.queryForList(sb.toString());
			log.info("待发送oa的数据"+list.size());
			try {
				for(int i=0;i<list.size();i++){
					String context = new File(getClass().getClassLoader().getResource("").toURI()).getPath();
					Map map=(Map) list.get(i);
					String sqdw=(String) map.get("bus_memo1");
					String creator=(String) map.get("creator");
					String filePath=(String) map.get("path");
					String filenum=(String) map.get("file_num");//文号
					String docid=(String) map.get("id");
					log.info("docid"+docid+"创建人:"+creator+"filePath"+filePath);
					context=context.substring(0,context.indexOf("WEB-INF")-1);
					String filepath=context+filePath;
					filepath=filepath.replace("/",File.separator);
					log.info("filepath------------>"+filepath);
					try {
						//查询用户的用户编码
						String usersql="from OmUser where userName='"+creator+"'";
						List<OmUser> users=this.omUserDao.find(usersql);
						if(users.size()>0){
							OmUser userdata= users.get(0);
							String userCode=userdata.getUserCode();
							log.info("filepath------------>"+filepath+sqdw+",行政许可决定书,"+"userCode:"+userCode);
							String title="";
							if(StringUtils.isNotBlank(filenum)){
								title="准予行政许可决定书("+filenum+")";
							}else{
								title=sqdw+"行政许可决定书";
							}
							
							String result=WSClient.invoke(filepath,title, userCode);
							log.info("发送oa文件返回结果"+result);
							//if("Success".equals(result)){
							log.info("开始修改决定书的状态");
							//YwPrintDoc doc=(YwPrintDoc) ywPrintDocDao.get(Long.valueOf(docid));
							String hql = "update YwPrintDoc t set t.sendoa='1' where t.id=:id";
							if(!"Success".equals(result)){
								 hql = "update YwPrintDoc t set t.sendoa='2' where t.id=:id";
							}
							
							Query query = this.omUserDao.getSession().createQuery(hql);
							query.setLong("id",Long.valueOf(docid));
							query.executeUpdate();
							
							//String docsql="update YW_PRINT_DOC set sendoa='1' where id="+Long.valueOf(docid);
							//this.updateDateBase(docsql);
							//doc.setSendoa("1");//改为已发送
							//ywPrintDocDao.save(doc);
							//}
						}
					} catch (Exception e) {
						e.printStackTrace();
						log.error("发送oa出现文件错误"+e);
					}
				}
			} catch (Exception e) {
				log.error("发送出现文件错误"+e);
			}
			
		}

		/**
		 * 简单SQL查询  
		 * 
		 * @param sql
		 * @return
		 */
		public  List queryForList(String sql) {
			Session session=this.ywPrintDocDao.getSession();
			Connection conn = null;
			Statement st = null;
			ResultSet rs = null;
			List<Map> tempList = new ArrayList<Map>();
			try {
				long timeBefore = System.currentTimeMillis();
				conn = session.connection();
				st = conn.createStatement();
				rs = st.executeQuery(sql);
				ResultSetMetaData meta = rs.getMetaData();
				int columnCount = meta.getColumnCount();
				while(rs.next()) {
					Map<String, String> map = new LinkedHashMap<String, String>();
					for(int i=1; i<=columnCount; i++) {
						String colName = meta.getColumnLabel(i).toLowerCase();
						String colValue = rs.getString(i);
						map.put(colName, colValue);
					}
					tempList.add(map);
				}
			
			}catch(Exception e) {
				log.error("查找异常--"+sql, e);
			}finally {
					try {
						if(st!=null){
							st.close();
						}
						if(rs!=null){
							rs.close();
						}
						if(conn!=null){
							conn.close();
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
			
			return tempList;
		}
		/**
		 * sql修改某张表
		 * @param sql
		 * @return
		 */
		public  int updateDateBase(String sql) {
			Session session=this.ywPrintDocDao.getSession();
			Connection conn = null;
			Statement st = null;
			int num = 0;
			try {
				long timeBefore = System.currentTimeMillis();
				conn = session.connection();
				st =conn.createStatement();
				num = st.executeUpdate(sql);
			}catch(Exception e) {
				log.error("更错误", e);
			}finally {
				try {
					if(st!=null){
						st.close();
					}
					if(conn!=null){
						conn.close();
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			return num;
		}
		
}
